package com.bybops.utils;

import android.content.Context;
import android.os.Environment;
import android.os.StatFs;
import android.text.TextUtils;
import android.util.Log;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.io.Writer;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import io.reactivex.exceptions.OnErrorNotImplementedException;


/**
 * Created by Administrator on 2016/12/28 0028.
 */

public class FileUtils {
    /**
     * 读取文件大小
     *
     * @param path
     * @return
     */
    public static long getFileSize(String path) {
        //读取文件大小
        String dir = path;
        long size = 0;
        if (dir != null) {
            File file = new File(dir);
            size = FileUtils.getDirSize(file);
        }
        return size;
    }

    /**
     * 复制单个文件
     *
     * @param oldPath String 原文件路径 如：c:/fqf.txt
     * @param newPath String 复制后路径 如：f:/fqf.txt
     * @return boolean
     */
    public static boolean copyFile(String oldPath, String newPath) {
        try {
            int bytesum = 0;
            int byteread = 0;
            File sceneVideoFile = new File(newPath);
            if (!sceneVideoFile.getParentFile().exists()) {
                sceneVideoFile.getParentFile().mkdirs();
            }
            File oldfile = new File(oldPath);
            if (oldfile.exists()) { //文件存在时
                InputStream inStream = new FileInputStream(oldPath); //读入原文件
                FileOutputStream fs = new FileOutputStream(newPath);
                byte[] buffer = new byte[1444];
                int length;
                while ((byteread = inStream.read(buffer)) != -1) {
                    bytesum += byteread; //字节数 文件大小
                    System.out.println(bytesum);
                    fs.write(buffer, 0, byteread);
                }
                inStream.close();
            }
            return true;
        } catch (Exception e) {
            System.out.println("复制单个文件操作出错");
            e.printStackTrace();
            return false;
        }

    }

    /**
     * 判断外部存储是否可用
     *
     * @return
     */
    public static boolean isExternalStorageAvailable() {

        return Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState());
    }

    /**
     * 取SD卡路径
     **/
    public static String getSDPath() {
        File sdDir = null;
        boolean sdCardExist = isExternalStorageAvailable(); // 判断sd卡是否存在
        if (sdCardExist) {
            sdDir = Environment.getExternalStorageDirectory(); // 获取根目录
        }
        if (sdDir != null) {
            return sdDir.toString();
        } else {
            return "";
        }
    }

    public static long getFileAvailable(String path) {
        if (TextUtils.isEmpty(path)) {
            return 0;
        }
        makeDir(path);
        if (path == null || !new File(path).exists()) {
            return 0;
        }

        StatFs stat = new StatFs(path);
        long blockSize = stat.getBlockSize();
        long availableBlocks = stat.getAvailableBlocks();
        return availableBlocks * blockSize;
    }


    public static String makeDir(String path_dir) {
        // 新建目录
        if (TextUtils.isEmpty(path_dir)) {
            return null;
        }
        File dir = new File(path_dir);
        if (!dir.exists()) {
            boolean success = dir.mkdirs();
            if (!success) {
                Log.e("test", "创建目录失败:" + path_dir);
                return null;
            } else {
                Log.i("test", "创建成功:" + path_dir);
            }
        }

        return path_dir;
    }


    /**
     * 获取系统默认SD卡的文件保存目录,没有就新建
     *
     * @return
     */
    public static String getDefaultLocalDir(String subDir) {

        String path_root = getSDPath();
        // String path_root = LiuLianApplication.sdCardRoot;
        if (path_root == null) {
            return null;
        }

        String path_dir = path_root + subDir;

        return makeDir(path_dir);
    }

    /**
     * 获取文件夹大小
     */
    public static long getDirSize(File dir) {
        if (dir == null || !dir.exists()) {
            return 0;
        }

        long size = 0;
        File[] flist = dir.listFiles();
        if (flist != null) {
            for (int i = 0; i < flist.length; i++) {
                if (flist[i].isDirectory()) {
                    size = size + getDirSize(flist[i]);
                } else {
                    size = size + flist[i].length();
                }
            }
        }

        return size;
    }

    /**
     * 删除文件夹
     */
    public static void deleteDir(File dir) {
        if (dir != null && dir.exists()) {
            File[] files = dir.listFiles();
            if (files != null) {
                for (File file : files) {
                    if (file.isDirectory()) {
                        deleteDir(file); // 递归删除子文件夹
                    } else {
                        file.delete(); // 删除子文件
                    }
                }
            }
            dir.delete(); // 最后删掉自己
        }
    }

    public static boolean isExitFile(String path) {
        File file = new File(path);
        return file.exists();
    }

    /**
     * 删除视频文件夹（点击下载的文件）
     */
    public static void deleteDownloadFiles(String path_dir) {
        // final String path_dir = FileDownloadUtil.getVideoDir(id);
        if (path_dir == null) {
            return;
        }
        deleteDir(new File(path_dir));
    }





    /**
     * 读取本地文件到字符串
     */
    public static String getLocalString(File file) {
        try {
            StringBuffer buffer = new StringBuffer();
            FileInputStream fis = new FileInputStream(file);
            InputStreamReader isr = new InputStreamReader(fis);
            Reader in = new BufferedReader(isr);

            int i;
            while ((i = in.read()) > -1) {
                buffer.append((char) i);
            }
            in.close();

            return buffer.toString();
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }


    /**
     * 将字符串写入本地文件
     */
    public static boolean saveStringToLocal(String str, File file_local) {
        try {
            FileOutputStream fos = new FileOutputStream(file_local);
            Writer out = new OutputStreamWriter(fos);
            out.write(str);
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    // 删除SD卡上的单个文件方法
    public static boolean delete(String SDPATH, String fileName) {
        //SDPATH目录路径，fileName文件名
        File file = new File(SDPATH + "/" + fileName);
        if (file == null || !file.exists() || file.isDirectory()) {
            return false;
        }
        file.delete();

        return true;
    }

    /**
     * 在指定的文件夹里创建一个文件名字, 名字是当前时间,指定后缀.
     *
     * @return
     */
    public static String createFile(String dir, String suffix) {
        Calendar c = Calendar.getInstance();
        int hour = c.get(Calendar.HOUR_OF_DAY);
        int minute = c.get(Calendar.MINUTE);
        int year = c.get(Calendar.YEAR);
        int month = c.get(Calendar.MONTH) + 1;
        int day = c.get(Calendar.DAY_OF_MONTH);
        int second = c.get(Calendar.SECOND);
        int millisecond = c.get(Calendar.MILLISECOND);
        year = year - 2000;
        String name = dir;
        File d = new File(name);

        // 如果目录不中存在，创建这个目录
        if (!d.exists())
            d.mkdirs();
        name += "/";


        name += String.valueOf(year);
        name += String.valueOf(month);
        name += String.valueOf(day);
        name += String.valueOf(hour);
        name += String.valueOf(minute);
        name += String.valueOf(second);
        name += String.valueOf(millisecond);
        if (suffix.startsWith(".") == false) {
            name += ".";
        }
        name += suffix;

        try {
            Thread.sleep(1);  //保持文件名的唯一性.
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        File file = new File(name);
        if (file.exists() == false) {
            try {
                file.createNewFile();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        return name;
    }



    /**
     * 获取指定文件夹下的文件
     */
    public static List<String> getFiles(File file, int size) {
        if (size <= 0) {
            return null;
        }
        if (file == null) {
            return null;
        }
        if (file.exists()) {
            List<String> list = new ArrayList<>();
            File[] files = file.listFiles();
            for (File file2 : files) {
                if (!file2.isDirectory()) {
                    list.add(file2.getAbsolutePath());
                }
            }
            return getSelectSizeList(list, size);
        }
        return null;
    }

    /**
     * 获取指定个数的list
     *
     * @return
     */
    public static List<String> getSelectSizeList(List<String> list, int size) {
        try {
            if (list == null || list.size() == 0) {
                return list;
            }
            int coverSize = list.size();
            if (coverSize == size) {
                return list;
            }
            int mult = coverSize - size;
            if (mult > 0) {
                for (int i = 0; i < mult; i++) {
                    list.remove(0);
                }
            } else {
                mult = Math.abs(mult);
                String item = list.get(coverSize - 1);
                for (int i = 0; i < mult; i++) {
                    list.add(item);
                }
            }
        } catch (OnErrorNotImplementedException e) {

        } catch (IndexOutOfBoundsException e) {

        }
        return list;
    }




    public static void copyFilesFromAssets(Context context, String assetsPath, String savePath) {
        try {
            String fileNames[] = context.getAssets().list(assetsPath);// 获取assets目录下的所有文件及目录名
            if (fileNames.length > 0) {// 如果是目录
                File file = new File(savePath);
                file.mkdirs();// 如果文件夹不存在，则递归
                for (String fileName : fileNames) {
                    copyFilesFromAssets(context, assetsPath + "/" + fileName,
                            savePath + "/" + fileName);
                }
            } else {// 如果是文件
                InputStream is = context.getAssets().open(assetsPath);
                FileOutputStream fos = new FileOutputStream(new File(savePath));
                byte[] buffer = new byte[1024];
                int byteCount = 0;
                while ((byteCount = is.read(buffer)) != -1) {// 循环从输入流读取
                    // buffer字节
                    fos.write(buffer, 0, byteCount);// 将读取的输入流写入到输出流
                }
                fos.flush();// 刷新缓冲区
                is.close();
                fos.close();
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

}
